// globalMethods.js
export default {
	
		// 注册$showPrompt到Vue原型上，以方便全局调用
		app.config.globalProperties.$showPrompt = function(option) {
			if (typeof option === 'object') {
				// #ifndef H5
				// if (option.hideTabBar) {
				// 	wx.hideTabBar();
				// }
				// #endif
				app.config.globalProperties.$store.commit('showPrompt', option)
			} else {
				throw "配置项必须为对象传入的值为：" + typeof option;
			}
		}
    // 定义全局方法
		app.config.globalProperties.$goURl = (url) => {//全局跳转封装
			if (url.indexOf('/pages/') != -1) {
				if(url.indexOf('/pages/cat/cat') != -1||url.indexOf('/pages/index/index') != -1||url.indexOf('/pages/vicinity/vicinity') != -1){
					uni.switchTab({
						url: url
					})
				}else{
					uni.navigateTo({
						url: url
					})
				}
			} else if (url.indexOf('http://') != -1) {
				uni.setStorageSync('appletid',0)
				uni.setStorageSync('applet',url)
				uni.navigateTo({
					url:'/pages/applet/applet'
				})
			} else {
				// #ifndef MP-WEIXIN
				uni.showToast({
					icon: 'none',
					title: '暂未开放,敬请期待'
				})
				// #endif
			}
		}
		app.config.globalProperties.$evalPro=(str)=> {//已废弃
		    var Fn = Function;
		    return new Fn('return ' + str)();
		}
		app.config.globalProperties.$toFiexd = (num,index) => {//保留小数
			return Number(num).toFixed(index)
		}
		app.config.globalProperties.$clearTime= (time) => {//处理时间
			return time.replace('T',' ').split('.')[0]
		}
		app.config.globalProperties.$isIos= () => {//判断是否ios
			let platform = uni.getSystemInfoSync().platform;
			return platform === 'ios'
		}
		app.config.globalProperties.$isAuto = () => {//是否登录
			let token = ''
			try {
				token = uni.getStorageSync('userInfo').token
			} catch (e) {
				
			}
			if(token){
				return true
			}else{
				return false
			}
		}
		app.config.globalProperties.$userInfo = (data) => {//全局接口请求
			let token = ''
			try {
				token = uni.getStorageSync('userInfo').token
			} catch (e) {
				
			}
			uni.request({
				url: app.config.globalProperties.$baseurl +'api/user_info/',
				method: 'GET',
				header: {
					'token': token
				},
				success: res => {
					if (res.statusCode == 200) {
						uni.setStorageSync('userInfo',res.data.data)
						data.success(res.data);
					} else if (res.statusCode == 403) {
						uni.reLaunch({
							url: '/pages/login/login'
						});
					} else {
		
					}
				},
				fail(e) {
				}
			});
		}
		app.config.globalProperties.$Uplode = (uploadSuccess) => {//全局上传图片(uploadSuccess回调函数)
			let token = ''
			try {
				token = uni.getStorageSync('userInfo').token
			} catch (e) {
				
			}
			uni.request({
				url: app.config.globalProperties.$baseurl + 'api/token/',
				method: 'GET',
				header: {
					'token': token
				},
				success: res => {
					let upload = res.data.data
					setTimeout(()=>{
						uni.chooseImage({
							count: 1, //默认9
							sizeType: ['original', 'compressed'],
							sourceType: ['album', 'camera '],
							success: (ress) => {
								console.log(ress,"图片信息")
								let type
								// #ifdef APP-PLUS
								type = ress.tempFilePaths[0].split('.')
								type = type[type.length - 1]
								// #endif	
								// #ifndef APP-PLUS
									type = ress.tempFiles[0].name.split('.')
									type = type[type.length - 1]
								// #endif	
								uni.uploadFile({
									url: upload.upload, //仅为示例，非真实的接口地址
									filePath: ress.tempFilePaths[0],
									name: 'file',
									header: {
										token: upload.token
									},
									formData: {
										key: app.config.globalProperties.$template + '/' + String(Math.round(new Date() / 1000)) + String(parseInt(Math.random() *10000)) + '.' + type,
										token: upload.token
									},
									header: {
										token: upload.token
									},
									success: (uploadFileRes) => {
										uploadSuccess(upload.url + JSON.parse(uploadFileRes.data).key)
									}
								});
							},
							fail() {
								console.log(fail)
								uni.showToast({
									icon:'none',
									title:'123'
								})
							}
						});
					},100)
		
				},
				fail(e) {
				}
		
			});
		}
		app.config.globalProperties.$UplodeVideo = (uploadSuccess) => {//全局上传图片(uploadSuccess回调函数)
			let token = ''
			try {
				token = uni.getStorageSync('userInfo').token
			} catch (e) {}
		
			uni.request({
				url: app.config.globalProperties.$baseurl + 'api/token/',
				method: 'GET',
				header: {
					'token': token
				},
				success: res => {
					console.log(res)
					let upload = res.data.data
					setTimeout(()=>{
						uni.chooseVideo({
							count: 1, //默认9
							sizeType: ['original', 'compressed'],
							sourceType: ['album', 'camera '],
							success: (ress) => {
								let type
								// #ifdef APP-PLUS
									type = ress.tempFilePaths[0].split('.')
									type = type[type.length - 1]
								// #endif	
								// #ifndef APP-PLUS
									type = ress.tempFiles[0].name.split('.')
									type = type[type.length - 1]
								// #endif	
								uni.uploadFile({
									url: upload.upload, //仅为示例，非真实的接口地址
									filePath: ress.tempFilePath,
									name: 'file',
									header: {
										token: upload.token
									},
									formData: {
										key: app.config.globalProperties.$template + '/' + String(Math.round(new Date() / 1000)) + String(parseInt(Math.random() *10000)) + '.' + type,
										token: upload.token
									},
									header: {
										token: upload.token
									},
									success: (uploadFileRes) => {
										uploadSuccess(upload.url + JSON.parse(uploadFileRes.data).key)
									}
								});
							},
							fail() {
								console.log(fail)
							}
						});
					
					},100)
				},
				fail(e) {
				}
		
			});
		}
		app.config.globalProperties.$request = async (data) => {  
					let token = '';  
					try {  
							const userInfo = uni.getStorageSync('userInfo');  
							if (userInfo && userInfo.token) {  
									token = userInfo.token;  
							}  
					} catch (e) {  
							//TODO handle the exception  
							console.error('Error getting token from storage:', e);  
					}  
					const response = await new Promise((resolve, reject) => {  
						uni.request({  
								url: app.config.globalProperties.$baseurl + data.url,  
								method: data.method,  
								data: data.method === 'GET' ? {} : JSON.stringify(data.data), // 注意：GET 请求通常不使用 data 字段发送数据  
								params: data.method === 'GET' ? data.data : {}, // 注意：params 用于 GET 请求的查询参数  
								header: {  
										'token': token  
								},  
								success: res => {  
										if (res.statusCode === 200) {  
												resolve(res.data);  
												reject(res);
										} else  if (error.statusCode === 403) {  // 处理错误情况，例如重新登录、显示错误信息等  
										uni.setStorageSync('userInfo', {});  
										// #ifdef MP-WEIXIN
											uni.switchTab({
													url: '/pages/personal/index'  
											});  
										// #endif
										// #ifndef MP-WEIXIN
										uni.reLaunch({
												url: '/pages/login/login'  
										});  
										// #endif
										} else if (error.statusCode === 400) {  
												uni.reLaunch({  
														url: '/pages/stop/stop'  
												});  
										} else {  
												// 处理其他错误情况  
												console.error('Request failed:', error);  
										}  
								},  
								fail: e => {  
										reject(e);  
								}  
						});  
				});  
			return response; // 返回响应数据，以便在 async 函数外部使用  
		};
		app.config.globalProperties.$SHOPrequest = (data) => {//全局接口请求
			let token = ''
			try {
				token = uni.getStorageSync('businessToken')
			} catch (e) {
				//TODO handle the exception
			}
		
			uni.request({
				url: app.config.globalProperties.$SHOPbaseurl + data.url,
				method: data.method,
				data: JSON.stringify(data.data),
				header: {
					'business': token
				},
				success: res => {
					// uni.hideLoading();
					if (res.statusCode == 200) {
						data.success(res.data);
					} else if (res.statusCode == 403) {
						uni.switchTab({
							url: '/pages/personal/index'
						});
					} else {
						// #ifndef  MP-WEIXIN 
						//  #endif 
					}
				},
				fail(e) {
		
				}
		
			});
		}
};
